<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\model\User as UserModel;
use app\admin\model\Template as TemplateModel;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\facade\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * 标签管理
 *
 * @icon fa fa-circle-o
 */
class Label extends Backend
{

    /**
     * Label模型对象
     * @var \app\admin\model\Label
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Label;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("itemList", $this->model->getItemList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * Selectpage搜索.
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = $list->toArray();
            foreach ($list as &$item) {
                $item['usernum'] = $item['templatenum'] = '-';
                if($item['type']==1){
                    $item['usernum'] = (new UserModel())->where('level', 'like', "%{$item['id']}%")->count();
                }else{
                    $item['templatenum'] = (new TemplateModel())->where('user_tags', 'like', "%{$item['id']}%")->count();
                    $item['usernum'] = (new UserModel())->where('label_ids', 'like', "%{$item['id']}%")->count();
                }

            }
            $result = ['total' => $total, 'rows' => $list];
            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $params['func'] = implode(',', $params['func']);
                    $result = $this->model->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function addremove()
    {
        if ($this->request->isPost()) {

            $row = $this->request->post('row/a');
            $oper_type = $row['oper-type']; //1 打标 2去标
            if (empty($row['file_url'])) {
                $this->error('未上传文件');
            }

            $file_path_arr = explode('uploads', $row['file_url']);
            $file_path_link = public_path() . 'uploads' . $file_path_arr[1];

            $ext = pathinfo($file_path_link, PATHINFO_EXTENSION);
            if (!in_array($ext, ['xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            //加载文件
            $insert = [];
            $fields = [];
            try {
                if (!$PHPExcel = $reader->load($file_path_link)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $insert[] = $values;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }

            if ($fields[1] != '手机号') {
                $this->error("表头{$fields[1]}应为【手机号】");
            }
            if ($fields[2] != '用户ID') {
                $this->error("表头{$fields[2]}应为【用户ID】");
            }
            if ($fields[3] != '模板ID') {
                $this->error("表头{$fields[3]}应为【模板ID】");
            }
            if ($fields[4] != '标签') {
                $this->error("表头{$fields[4]}应为【标签】");
            }

            if (empty($insert)) {
                $this->error("未检测到数据");
            }
            $label = $this->model->select()->toArray();
            $label = array_column($label, null, 'name');
            $userModel = new User();
            $teplateModel = new TemplateModel();
            foreach ($insert as $key => &$val) {
                $val['uinfo'] = $val['template'] = [];
                $val['datatype'] = '';
                $label_list = explode(',', $val[4]);
                if (empty($label_list)) {
                    $this->error("第" . ($key + 1) . '行标签信息不存在');
                }


                if ($val[1] || $val[2]) {
                    //给用户打标

                    if ($val[1]) {
                        $uinfo = $userModel->where('mobile', $val[1])->find();

                    } else {
                        $uinfo = $userModel->where('id', $val[2])->find();
                    }
                    if (empty($uinfo)) {
                        $this->error("第" . ($key + 1) . '行用户信息不存在');
                    }
                    $val['uinfo'] = $uinfo;
                    $val['datatype'] = 'user';
                }

             if ($val[3]){
                    //给模板打标
                    $temp = $teplateModel->where('id', $val[3])->find();
                    if (empty($temp)) {
                        $this->error("第" . ($key + 1) . '行模板信息不存在');
                    }
                    $val['template'] = $temp;
                    $val['datatype'] = 'temp';
                }

                //处理标签
                foreach ($label_list as $lab) {
                    if (!isset($label[$lab]) || ($label[$lab]['type'] == 1 && $val['datatype'] == 'temp')) {
                        $this->error("第" . ($key + 1) . '行【' . $lab . '】标签在系统内不存在或者不属于该类型');
                    }
                }
                $val['label_list'] = $label_list;

            }


            if ($oper_type == 1) {
                foreach ($insert as $key => $val) {
                    $label_list = $val['label_list'];
                    if ($val['datatype'] == 'temp') {
                        $user_tags = explode(',', $val['template']['user_tags']);
                        foreach ($label_list as $lab) {
                            $user_tags[] = $label[$lab]['id'];
                        }
                        $user_tags = array_unique($user_tags);
                        $teplateModel->where('id', $val['template']['id'])->update(['user_tags' => implode(',', $user_tags)]);
                    } else {
                        $label_ids=explode(',', $val['uinfo']['label_ids']);
                        foreach ($label_list as $lab) {
                            if ($label[$lab]['type'] == 1) {
                                $userModel->where('id', $val['uinfo']['id'])->update(['level' => $label[$lab]['id']]);
                            }else{
                                $label_ids[] = $label[$lab]['id'];
                            }
                        }
//                        dump($label_ids);die;
                        $label_ids = array_unique($label_ids);
                        $label_ids &&   $userModel->where('id', $val['uinfo']['id'])->update(['label_ids' => implode(',',$label_ids)]);
                    }
                }
            } else {
                //去标
                foreach ($insert as $key => $val) {
                    $label_list = $val['label_list'];
                    if ($val['datatype'] == 'temp') {
                        $user_tags = explode(',', $val['template']['user_tags']);
                        foreach ($label_list as $lab) {
                            $user_tags = array_diff($user_tags,[$label[$lab]['id']]);
                        }
                        $user_tags = array_unique($user_tags);
                        $teplateModel->where('id', $val['template']['id'])->update(['user_tags' => implode(',', $user_tags)]);
                    } else {
                        $label_ids=explode(',', $val['uinfo']['label_ids']);
                        foreach ($label_list as $lab) {
                            if ($label[$lab]['type'] == 1) {
                                $userModel->where('id', $val['uinfo']['id'])->where('level',$label[$lab]['id'])->update(['level' => 0]);
                            }else{
                                $label_ids = array_diff($label_ids,[$label[$lab]['id']]);
                            }
                        }
                        $userModel->where('id', $val['uinfo']['id'])->update(['label_ids' => implode(',',$label_ids)]);
                    }
                }
            }
          $this->success();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $params['func'] = implode(',', $params['func']);
                    $result = $row->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }


}
